package com.wstuo.common.tools.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.moyosoft.exchange.Exchange;
import com.moyosoft.exchange.ExchangeServiceException;
import com.moyosoft.exchange.folder.ExchangeFolder;
import com.moyosoft.exchange.item.BodyType;
import com.moyosoft.exchange.item.ExchangeItem;
import com.moyosoft.exchange.item.ExchangeItemField;
import com.moyosoft.exchange.item.ItemsCollection;
import com.moyosoft.exchange.mail.ExchangeMail;
import com.moyosoft.exchange.mail.ExchangeMailbox;
import com.moyosoft.exchange.search.If;
import com.moyosoft.exchange.search.Restriction;
import com.wstuo.common.tools.dao.IEmailDAO;
import com.wstuo.common.tools.dto.EmailDTO;
import com.wstuo.common.tools.dto.EmailMessageDTO;
import com.wstuo.common.tools.dto.EmailServerDTO;
import com.wstuo.common.tools.entity.EmailMessage;
import com.wstuo.common.util.StringUtils;

/**
 * Exchange Services Class
 * @author WSTUO
 *
 */
public class ExchangeService implements IExchangeService{
	private final static Logger LOGGER = Logger.getLogger(ExchangeService.class);
	@Autowired
	private IEmailServerService emailServerService;
	@Autowired
	private IEmailService emailService;
	@Autowired
    private IEmailDAO emailDAO;
	
	private Exchange mExchange;
	private EmailServerDTO dto;
	
	private void init() throws ExchangeServiceException   {
		dto = emailServerService.findEmail();
		if(StringUtils.hasText(dto.getSpecifyConnectionUrl())){//判定是否使用指定的URL
			mExchangeSpecifyConnectionUrl(dto);//重构后，调用公共的方法
		}else{
			mExchangeHttps( dto);//重构后  调用公共的方法
		}
	}
	
	
	/**
	 * Exchange连接测试
	 * @param dto
	 * @return boolean
	 */
	@Transactional
	public boolean exchangeConnectionTest(EmailServerDTO dto){
		boolean result=true;
		try
		{
			if(StringUtils.hasText(dto.getSpecifyConnectionUrl())){//判定是否使用指定的URL
				mExchangeSpecifyConnectionUrl(dto);//重构后
			}else{
				mExchangeHttps( dto);
			}
		}catch(ExchangeServiceException ex){
			LOGGER.error("Exchange连接测试",ex);
			result=false;
		}
		return result;
		
	}
	/**
	 * 代码重构的公共方法
	 */
	private  void mExchangeHttps(EmailServerDTO dto) throws ExchangeServiceException{
		mExchange = new Exchange(
				dto.getExchangeHostName(),
				dto.getExchangeUserName(),
				dto.getExchangePassword(), 
				dto.getDomain(),
				dto.getUseHttps());
	}
	/**
	 *  代码重构的公共方法
	 * @param dto
	 * @throws ExchangeServiceException
	 */
	private void mExchangeSpecifyConnectionUrl(EmailServerDTO dto) throws ExchangeServiceException{
		mExchange = new Exchange(
				dto.getExchangeHostName(),
				dto.getExchangeUserName(),
				dto.getExchangePassword(), 
				dto.getDomain(),
				dto.getSpecifyConnectionUrl());
	}
	
	
	/**
	 * 邮件发送
	 */
	@Transactional
	public boolean sendEmail(EmailDTO dto){
		Boolean result=true;
		try {
			init();
			ExchangeMail mail = mExchange.createMail();
			mail.setToRecipients(dto.getTo());//接收人
			mail.setSubject(dto.getSubject());//邮件标题
			mail.setBody(dto.getContent(),BodyType.Html);//邮件内容
			mail.send();
			EmailMessage emailMessage = new EmailMessage();
			emailMessage.setFolderName("OUTBOX");
			BeanUtils.copyProperties(dto, emailMessage);
			emailMessage.setSendDate(new Date());//发送时间
			emailMessage.setFromUser(dto.getFrom());//发件人
			emailMessage.setToUser(receiveAddressToString(dto.getTo()));//接收人
			emailService.saveEmailMessages(emailMessage);//记录保存到数据
		} catch (ExchangeServiceException e) {
			LOGGER.error(e);
			result=false;
		}
		return result;
		
	
	}
	
	/**
	 * 邮件接收
	 * @throws ExchangeServiceException
	 */
	@Transactional
	public List<EmailMessageDTO> getInboxMail(){
		
		List<EmailMessageDTO> list = new ArrayList<EmailMessageDTO>();
		
		try {
			init();
			ExchangeFolder inbox;
			inbox = mExchange.getInboxFolder();
			EmailMessage emailMessage = emailDAO.findLastestReceiveDate(dto.getExchangeUserName());
			
			//查询条件
			Restriction restriction=null;
			if(emailMessage!=null && emailMessage.getReceiveDate()!=null){
				restriction=If.Message.DateTimeReceived.isAfter(emailMessage.getReceiveDate()).and().isNot(emailMessage.getReceiveDate());
			}
			
			ItemsCollection items = inbox.getItems().
				restrict(restriction).sortBy(ExchangeItemField.item_DateTimeReceived);
			
			
			for(ExchangeItem item : items)
			{
				ExchangeMail mail = (ExchangeMail) item;
				
				if(emailMessage==null || emailMessage.getReceiveDate().getTime()!=mail.getDateTimeReceived().getTime()){
					//保存到数据库
					EmailMessage em = new EmailMessage();
					em.setFolderName("INBOX");
					em.setSubject(mail.getSubject());
					em.setContent(mail.getBody());
					em.setFromUser(mail.getFromEmailAddress());
					em.setToUser(mailboxsToString(mail.getToRecipientsMailboxes()));
					em.setBcc(mailboxsToString(mail.getBccRecipientsMailboxes()));
					em.setCc(mailboxsToString(mail.getCcRecipientsMailboxes()));
					em.setSendDate(mail.getDateTimeSent());
					em.setReceiveDate(mail.getDateTimeReceived());
					emailDAO.merge(em);
					
					//返回List转请求
					EmailMessageDTO dto = new EmailMessageDTO();
					dto.setEmailMessageId(em.getEmailMessageId());
					dto.setSubject(mail.getSubject());
					dto.setContent(mail.getBody());
					dto.setFromUser(mail.getFromEmailAddress());
					list.add(dto);
				}
			}
		} catch (ExchangeServiceException e1) {
			LOGGER.error(e1);
		}
		
		
		return list;
	}
	
	/**
	 * 接收地址转换成String
	 * @param embs
	 * @return
	 * @throws ExchangeServiceException
	 */
	private String mailboxsToString(List<ExchangeMailbox> embs) throws ExchangeServiceException{
		
		StringBuffer sb =new StringBuffer("");
		if(embs!=null){
			for(ExchangeMailbox emb:embs){
				if(sb.toString().equals(""))
					sb.append(emb.getEmailAddress());
				else
					sb.append(";"+emb.getEmailAddress());
			}
		}
		return sb.toString();
	}
	
	/**
	 * 接收地址转List
	 * @param tos
	 * @return
	 */
	private String receiveAddressToString(List<String> tos){
		
		StringBuffer sb =new StringBuffer("");
		if(tos!=null){
			for(String to:tos){
				if(sb.toString().equals(""))
					sb.append(to);
				else
					sb.append(";"+to);
			}
		}
		return sb.toString();
		
	}
	
	
	
	
}
